<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <!-- 具名插槽 -->
        <template slot="before">
          <span>共{{ page.total }}条记录</span>
        </template>
        <template slot="after">
          <el-button size="small" type="danger" @click="exportData"
            >普通excel导出</el-button
          >
          <el-button size="small" type="info">复杂表头excel导出</el-button>
          <el-button
            size="small"
            type="success"
            @click="$router.push('import?type=user')"
            >excel导入</el-button
          >
          <el-button size="small" type="primary" @click="showDialog=true"
            >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格 -->
      <el-table border :data="list">
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column
          label="姓名"
          sortable=""
          prop="username"
        ></el-table-column>
        <el-table-column label="头像">
          <template slot-scope="{ row }">
            <img
              v-imgerror="require('@/assets/common/bigUserHeader.png')"
              :src="row.staffPhoto"
              alt=""
              style="
                width: 100px;
                height: 100px;
                padding: 10px;
                border-radius: 50%;
              "
              @click="showQrCode(row.staffPhoto)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="手机号"
          sortable
          prop="mobile"
        ></el-table-column>
        <el-table-column
          label="工号"
          sortable
          prop="workNumber"
        ></el-table-column>
        <el-table-column
          label="聘用形式"
          prop="formOfEmployment"
          sortable
          :formatter="formatEmployment"
        ></el-table-column>
        <el-table-column
          label="部门"
          prop="departmentName"
          sortable
        ></el-table-column>
        <el-table-column label="入职时间" prop="timeOfEntry" sortable>
          <template v-slot="{ row }">
            <!-- 将时间进行格式化 -->
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="enableState" sortable>
          <template slot-scope="{ row }">
            <el-switch :value="row.enableState === 1" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260px">
          <template slot-scope="{ row }">
            <el-button
              type="text"
              size="small"
              @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button
            >
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调职</el-button>
            <el-button type="text" size="small">离岗</el-button>
            <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="delEmployee(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          layout="prev, pager, next"
          :current-page="page.page"
          :page-size="page.size"
          :total="page.total"
          @current-change="changePage"
        ></el-pagination>
      </el-row>
    </div>
    <!-- 新增员工 -->
    <add-employees :showDialog.sync="showDialog"></add-employees>

    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas"></canvas
      ></el-row>
    </el-dialog>

    <!-- 角色弹层 -->
    <assign-role :userId='userId' :showRoleDialog.sync="showRoleDialog" ref="assignRole"></assign-role>
  </div>
</template>
<script>
import AddEmployees from "./components/add-employmees.vue";
import { getEmployeeList, delEmployee } from "@/api/employees";
import { formatDate } from "@/filters/index";
import EmployeesType from "@/api/constant/employees";
import QrCode from 'qrcode'
import assignRole from './components/assign-role.vue'
export default {
  components: { AddEmployees, assignRole },
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0,
      },
      showDialog: false,
      showCodeDialog: false, // 显示二维码弹层
      showRoleDialog: false,
      userId:""   // 员工的id
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    // 分配角色
    editRole(id){
      // 点击角色 传递员工的id  给该员工分配角色
      this.userId = id;
      // 调用子组件的方法  获取当前员工选中的角色
      this.$refs.assignRole.getUserDetailById(id);
      this.showRoleDialog = true;
    },
    // 格式化导出的聘用形式
    formatEmployment(row, column, cellValue, index) {
      //  格式化聘用形式
      const obj = EmployeesType.hireType.find((item) => item.id === cellValue);
      return obj ? obj.value : "未知";
    },
    // 获取员工列表
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList(this.page);
      // console.log(total);
      this.list = rows;
      this.page.total = total;
    },
    changePage(newPage) {
      // newPage是当前点击的页码
      this.page.page = newPage;
      // 重新渲染
      this.getEmployeeList();
    },
    async delEmployee(id) {
      try {
        await this.$confirm("确定要删除吗?");
        await delEmployee(id);
        this.getEmployeeList();
        this.$message.success("删除角色成功!");
      } catch (error) {
        console.log(error);
      }
    },
    // 导出员工列表
    exportData() {
      // 表头对应的关系
      const headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      // console.log(import('@/vendor/Export2Excel'))
      // 按需加载
      import("@/vendor/Export2Excel").then(async (excel) => {
        // console.log(excel, 'excel')

        // 重新获取员工数据
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total,
        });
        // 要将获取的到员工数据 转换为数组的形式 [{}] ==> [[]]
        const data = this.formatJson(headers, rows);
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: "员工信息表",
          autoWidth: true,
          bookType: "xlsx",
        });
      });
    },

    // 转换获取到的员工数据形式 [{}] ==> [[]]
    formatJson(headers, rows) {
      // [{username:"张三"}]  ==>  [['张三'],[]]
      return rows.map((item) => {
        return Object.keys(headers).map((key) => {
          if (
            headers[key] === "timeOfEntry" ||
            headers[key] === "correctionTime"
          ) {
            return formatDate(item[headers[key]]); //返回一个格式化之前的时间
          } else if (headers[key] === "formOfEmployment") {
            var en = EmployeesType.hireType.find(
              (obj) => obj.id === item[headers[key]]
            );
            return en ? en.value : "未知";
          }
          return item[headers[key]];
        });
      });
    },
    // 点击图片弹出二维码
    showQrCode(url) {
      // console.log(123);
      // 点击图片显示二维码
      if (url) {
        this.showCodeDialog = true;
        // 数据更新 页面的渲染时异步的
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url); //将地址转化为二维码
        });
      } else {
        this.$message.warning("用户还未上传头像");
      }
    },
  },
};
</script>
<style scoped>
</style>